// ProjectName: go-learn-demo
// PackageName: _9_xorm
// Description:
// Author: hy.bai
// Date: 2025-08-19 星期二 11:16

package xormybxb

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"log/slog"
	"time"
	"xorm.io/xorm"
	"xorm.io/xorm/log"
	"xorm.io/xorm/names"
)

var currentTimeStr = time.Now().Format("20060102150405")

// 数据库连接基本信息
const (
	DBTYPE    string = "mysql"
	USERNAME  string = "root"
	PASSWORD  string = "root"
	IPADDRESS string = "127.0.0.1"
	PORT      int    = 3308
	DBNAME    string = "ybxb"
)

// 定义一个全局变量,代表数据库连接对象
var MysqlEngine *xorm.Engine

// 创建数据库连接引擎
func InitEngine() {
	dataSourceName := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset:utf8mb4", USERNAME, PASSWORD, IPADDRESS, PORT, DBNAME)
	engine, err := xorm.NewEngine(DBTYPE, dataSourceName)
	// 设置日志级别,默认级别是Info
	engine.SetLogLevel(log.LOG_DEBUG)
	// 设置控台打印sql语句
	engine.ShowSQL(true)
	// 设置连接池的空闲数大小
	engine.SetMaxIdleConns(3)
	// 设置最大打开数
	engine.SetMaxOpenConns(5)
	if err != nil {
		slog.Error(fmt.Sprintf("创建数据库连接失败,原因是:%s", err.Error()))
	}
	if err = engine.Ping(); err != nil {
		slog.Error(fmt.Sprintf("测试数据库连接失败,原因是:%s", err.Error()))
	}
	engine.SetMapper(names.GonicMapper{})
	MysqlEngine = engine
}
